namespace Digitalmes.Application.Mes;

/// <summary>
/// 工艺路线项明细表服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "mes")]
public sealed class ProcRoutingItemService : IDynamicWebApiService
{
    private readonly SugarRepository<ProcRoutingItem> _thisRepository;

    public ProcRoutingItemService(SugarRepository<ProcRoutingItem> thisRepository)
    {
        _thisRepository = thisRepository;
    }

    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ProcRoutingItemDto>> GetPagesAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<ProcRoutingItemDto>>();
    }

    /// <summary>
    /// 根据工艺路线Id获取工艺集合
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ProcRoutingItemDto>> GetPagesByRoutingIdAsync(RoutingItemPageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .Includes(s => s.Routing)
            .Includes(s => s.Process)
            .Where(s => s.RoutingId == param.RoutingId)
            .OrderBy(m => m.Pos)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<ProcRoutingItemDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ProcRoutingItemDto> GetAsync(long id)
    {
        var model = await _thisRepository.GetByIdAsync(id);
        return model.Adapt<ProcRoutingItemDto>();
    }

    /// <summary>
    /// 根据工艺路线Id获取可用的工艺详细
    /// </summary>
    /// <param name="routingId"></param>
    /// <returns></returns>
    [HttpGet("{routingId}")]
    public async Task<List<ProcRoutingItemDto>> GetListByRoutingIdAsync(long routingId)
    {
        var list = await _thisRepository.AsQueryable()
            .OrderBy(s => s.Pos)
            .Where(s => s.RoutingId == routingId && !s.IsDisabled)
            .ToListAsync();
        return list.Adapt<List<ProcRoutingItemDto>>();
    }

    /// <summary>
    /// 根据工艺路线Id获取工艺数量
    /// </summary>
    /// <param name="routingId"></param>
    /// <returns></returns>
    [HttpGet("{routingId}")]
    public async Task<int> GetCountByRoutingIdAsync(long routingId)
    {
        return await _thisRepository.CountAsync(s => s.RoutingId == routingId);
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> AddAsync(ProcRoutingItemDto model)
    {
        // 同一路径下不同工序必须唯一
        if (await _thisRepository.IsAnyAsync(s => s.RoutingId == model.RoutingId && s.ProcessId == model.ProcessId))
        {
            Oops.ThrowBah(ErrCode.E4007);
        }

        int count = await _thisRepository.CountAsync(s => s.RoutingId == model.RoutingId);
        model.Pos = count + 1;
        return await _thisRepository.InsertAsync(model.Adapt<ProcRoutingItem>());
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> ModifyAsync(ProcRoutingItemDto model)
    {
        if (await _thisRepository.IsAnyAsync(s => s.RoutingId == model.RoutingId && s.ProcessId == model.ProcessId && s.Id != model.Id))
        {
            Oops.ThrowBah(ErrCode.E4007);
        }

        return await _thisRepository.UpdateAsync(model.Adapt<ProcRoutingItem>());
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody] long id) 
    {
        // 删除项后所有的项重新排序
        var item = await _thisRepository.GetByIdAsync(id);
        if (item is null)
        {
            return true;
        }

        // 重新排序删除项下方的数据
        var downItems = await _thisRepository.GetListAsync(s => s.RoutingId == item.RoutingId && s.Pos > item.Pos);
        if (downItems.Any())
        {
            downItems.ForEach(s =>
            {
                s.Pos--;
            });
            await _thisRepository.AsUpdateable(downItems).UpdateColumns(s => new { s.Pos }).ExecuteCommandAsync();
        }

        await _thisRepository.DeleteByIdAsync(id);

        return true;
    }

    /// <summary>
    /// 向上排序
    /// </summary>
    /// <returns></returns>
    [HttpPut]
    public async Task UpSortAsync(SortParam param)
    {
        // 判断是否为第一个
        var item = await _thisRepository.GetByIdAsync(param.Id);
        if (item.Pos == 1)
        {
            return;
        }

        // 此项与上一项 Pos 交换顺序
        List<ProcRoutingItem> updateItems = new(2) 
        { 
            item,
        };
        
        var upItem = await _thisRepository.GetFirstAsync(s => s.RoutingId == item.RoutingId && s.Pos == item.Pos - 1);
        if (upItem != null)
        {
            upItem.Pos++;
            updateItems.Add(upItem);
        }

        item.Pos--;
        await _thisRepository.AsUpdateable(updateItems).UpdateColumns(s => new { s.Pos }).ExecuteCommandAsync();
    }

    /// <summary>
    /// 向下排序
    /// </summary>
    /// <returns></returns>
    [HttpPut]
    public async Task DownSortAsync(SortParam param)
    {
        // 判断是否为最后一个
        var item = await _thisRepository.GetByIdAsync(param.Id);
        var downItem = await _thisRepository.GetFirstAsync(s => s.RoutingId == item.RoutingId && s.Pos == item.Pos + 1);
        if (downItem == null)
        {
            return;
        }

        // 此项与下一项 Pos 交换顺序
        downItem.Pos--;
        item.Pos++;
        await _thisRepository.AsUpdateable(new[] { downItem, item }).UpdateColumns(s => new { s.Pos }).ExecuteCommandAsync();
    }
}
